package com.ltedu.common.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ltedu.common.contants.AuthConstants;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @className: SecurityUtils
 * @auther: Jerry
 * @date: 2020/12/15 17:19
 * @desctiption: 权限获取工具类
 * @version: 1.0
 */
public class SecurityUtils {

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 获取当前登录用户
     *
     * @return {@link JSONObject}
     */
    public static JSONObject getCurentUser() {
        String userStr = ServletUtils.getRequest().getHeader(AuthConstants.AUTHORIZATION);
        System.out.println("userStr:" + userStr);
        JSONObject jsonObject = JSONUtil.parseObj(userStr);
        return jsonObject;
    }

    /**
     * 获取当前登录用户id
     *
     * @return {@link Long}
     */
    public static Long getUserId() {
        Long id = getCurentUser().getLong(AuthConstants.USER_ID_KEY);
        System.out.println("id:" + id);
        return id;
    }
}
